import { authApi } from '../../api/auth'
import { authLogin } from '/store/actions'
import { GlobalData } from '/store/state'
import { $event, $storage } from '/utils'

Component({
  properties: {
    closable: Boolean,
  },
  data: {
    show: false,
    type: 'guest', // 获取类型 guest / register
    code: '',
    /** 后端绑定账号所需内容 (来源于后端) */
    form: {} as BindUserPayload,
    name: '{{NAME}}',
    canIUseGetUserProfile: false,
  },
  pageLifetimes: {
    show() {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      //@ts-ignore
      if (wx.getUserProfile) {
        this.setData({
          canIUseGetUserProfile: true,
        })
      }
      wx.login({
        success: (res) => {
          this.setData({
            code: res.code,
          })
          // this.open()
        },
      })
      $event.on('login', this, () => {
        this.open()
      })
      $event.on('login:close', this, () => {
        this.close(true)
      })
    },
    hide() {
      this.close(true)
    },
  },

  methods: {
    emptyHandler() {
      console.log('empty')
    },
    open() {
      const registerInfo = $storage.get<GetUserAccountRegisterCallback>('registerInfo')
      console.log('open')
      if (registerInfo) {
        this.setData({
          type: 'register',
          form: registerInfo as any,
          show: true,
        })
      } else {
        this.setData({
          show: true,
        })
      }
    },
    close(force = false) {
      if (this.data.closable || force) {
        this.setData({
          show: false,
        })
      }
    },
    getWechatUserInfo() {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success: () => {
                this.handleGetUserinfo()
              },
              fail: (e) => {
                wx.showModal({
                  title: '温馨提示',
                  content: '请开启用户信息获取权限，否则应用将无法正常使用',
                  success: () => {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.userInfo']) {
                          this.handleGetUserinfo()
                        }
                      },
                    })
                  },
                })
              },
            })
          } else {
            this.handleGetUserinfo()
          }
        },
        fail: (error) => {
          wx.showToast({
            title: '分享页仅提供展示',
          })
        },
      })
    },

    // 真正获取用户信息
    handleGetUserinfo() {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      //@ts-ignore
      wx.getUserProfile({
        desc: '用于完善用户资料',
        lang: 'zh_CN',
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        //@ts-ignore
        success: (res) => {
          GlobalData.userInfo = res.userInfo
          console.log(res.userInfo)
          // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
          //@ts-ignore
          this.getDomoUser(res)
        },
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        //@ts-ignore
        fail: (e) => {
          wx.showToast({
            title: '获取用户息失败，请从新操作',
          })
        },
      })
    },
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    //@ts-ignore
    getUserInfo(e) {
      // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
      GlobalData.userInfo = e.detail.userInfo
      this.getDomoUser(e.detail)
    },

    // 获取用户openid
    async getDomoUser(res: WechatMiniprogram.GetUserInfoSuccessCallbackResult) {
      wx.showLoading({ title: '正在登录' })
      try {
        const isLogin = await authLogin(this.data.code, res)
        if (isLogin) {
          $event.emit('after:login')
          this.close(true)
          // 9-25修改，授权登录完毕，获取手机号码
          this.setData({
            type: 'register',
            form: res as any,
          })
          this.open()
        } else {
          this.setData({
            type: 'register',
            form: res as any,
          })
        }
      } catch (error) {
        wx.showToast({
          title: error.data.message,
          icon: 'none',
        })
      }
      wx.hideLoading()
    },
    async getWechatUserPhone(e: WechatMiniprogram.CustomEvent) {
      const iv = e.detail.iv
      const openid = GlobalData.openId
      const encryptedData = e.detail.encryptedData
      wx.login({
        success: function (res) {
          authApi
            .getUserPhone({
              code: res.code,
              iv: iv,
              encryptedData: encryptedData,
              openid: openid,
              signature: '',
            })
            .then((res2) => {
              if (res2.type === 'alert' || res2.type === '"error"') {
                wx.showModal({
                  title: '错误',
                  content: '',
                })
                return
              } else {
                console.log(res2.phone)
                if (res2.phone) {
                  GlobalData.phone = res2.phone
                  $event.emit('after:login')
                  console.log(GlobalData.phone)
                }
              }
            })
        },
      })
      // try {
      // const registerInfo = $storage.get('registerInfo') as GetUserAccountRegisterCallback

      // const params = {
      //   code: detail.code,
      //   encryptedData: detail.encryptedData,
      //   iv: detail.iv,
      // }
      // console.log(params)
      // const res = await authApi.bindUser({
      //   ...this.data.form,
      //   encryptedData: detail.encryptedData,
      //   iv: detail.iv,
      //   payload: registerInfo.payload,
      //   decrypt: registerInfo.decrypt,
      //   openid: openid,
      // })

      // this.getDomoUser(e.detail)
      // setAccessToken(res.token, res.expires_in)
      // $storage.remove('registerInfo') // 2024/7/24日修改
      // $event.emit('after:registerInfo')
      // await getDomoUser()
      // $event.emit('after:login')
      this.close(true)
      // }
    },
    cancel() {
      this.close(true)
    },
  },
})
